package com.keon.jianbao.api;

import android.app.Activity;
import android.support.v4.app.Fragment;

import com.keon.jianbao.AppManager;
import com.keon.jianbao.R;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.ui.activity.LoginActivity;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;

/**
 * Created by keon on 2015/9/6.
 */
public class SimpleHandler extends AsyncHttpResponseHandler {

    BaseActivity context;

    public SimpleHandler() {
//        this.context = (BaseActivity) AppManager.getAppManager().currentActivity();
    }

    public SimpleHandler(Activity context) {
        this.context = (BaseActivity) context;
    }

    public void setContext(Activity context) {
        this.context = (BaseActivity) context;
    }

    public void setContext(Fragment context) {
        this.context = (BaseActivity) context.getActivity();
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        context.showToast(R.string.common_error_network);
    }

    @Override
    public void onFinish() {
//        super.onFinish();
        context.hideWaitDialog();
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        try {
            Result result = new Result(responseBody);
            if (result.getStatus() == -2 || result.getStatus() == -1) {
                context.showToast(R.string.common_error_bad_token);
                AppManager.getAppManager().finishActivity();
                context.jump(LoginActivity.class);
                return;
            } else if (result.getStatus() < 1) {
                context.showToast(result.getTips());
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}
